//
//  DateUtil.swift
//  Game
//
//  Created by woniu on 2025/8/27.
//

import Foundation

struct DateUtil{
    
    //获取通用(已通过测试，不要乱修改，否则要测试)
    static func getFormat()->DateFormatter{
        let formatter = DateFormatter()
        formatter.locale = NSLocale.system
        formatter.calendar = Calendar(identifier: .gregorian)
        return formatter
    }
    
    ///获取当前日期字符串，默认 yyyy-MM-dd
    static func currentDate(format:String = "yyyy-MM-dd") -> String {
        let date = Date()
        let timeFormatter = getFormat()
        timeFormatter.dateFormat = format
        let valDate = timeFormatter.string(from: date)
        return valDate
    }
    
    ///获取当前日期时间时间，默认 yyyy-MM-dd HH:mm:ss
    static func currentDateTime(format:String="yyyy-MM-dd HH:mm:ss") ->String {
        return self.currentDate(format: format)
    }
    
    
    /// 时间转时间戳 "2019-12-29 08:00:00"
    static func formatToString(stringTime:String, dateFormat:String? = "yyyy-MM-dd HH:mm:ss")->String {
        
        let dfmatter = getFormat()
        dfmatter.dateFormat = dateFormat
        guard let date = dfmatter.date(from: stringTime)else {return ""}
        
        let timeFormatter = getFormat()
        timeFormatter.dateFormat = dateFormat
        let valDate = timeFormatter.string(from: date)
        
        return valDate
    }
    
    ///返回时间（今天，昨天....）
    static func getCHString(dateTimeStr:String) -> String{
        if dateTimeStr.isEmpty{
            return ""
        }
        let dfmatter = getFormat()
        dfmatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        guard let date = dfmatter.date(from: dateTimeStr)else {return dateTimeStr}
        
        let formatter = DateFormatter()
        if date.isToday() {
            //是今天
            formatter.dateFormat = "（今天）HH:mm:ss"
            return formatter.string(from: date)
            
        }else if date.isYesterday(){
            //是昨天
            formatter.dateFormat = "（昨天）HH:mm:ss"
            return formatter.string(from: date)
        }else if date.isSameWeek(){
            //是同一周
            let week = date.weekdayStringFromDate()
            formatter.dateFormat = "（\(week)）HH:mm:ss"
            return formatter.string(from: date)
        }else{
            formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            return formatter.string(from: date)
        }
    }
}
